package com.fang.security.config;

import com.fang.security.security.filter.JwtAuthenticationTokenFilter;
import com.fang.security.security.handler.*;
import com.fang.security.security.service.SecurityAuthenticationProvider;
import com.fang.security.security.service.SecurityPermissionEvaluator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler;

import javax.annotation.Resource;

/**
 * @Description
 * @Author Bernie
 * @Date 2024/4/1 17:32
 **/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) //开启权限注解,默认是关闭的
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    //登录成功处理逻辑
    @Resource
    CustomizeAuthenticationSuccessHandler authenticationSuccessHandler;

    //登录失败处理逻辑
    @Resource
    CustomizeAuthenticationFailureHandler authenticationFailureHandler;

    //权限拒绝处理逻辑
    @Resource
    CustomizeAccessDeniedHandler accessDeniedHandler;

    //匿名用户访问无权限资源时的异常
    @Resource
    CustomizeAuthenticationEntryPoint authenticationEntryPoint;

    //登出成功处理逻辑
    @Resource
    CustomizeLogoutSuccessHandler logoutSuccessHandler;

    @Resource
    SecurityAuthenticationProvider securityAuthenticationProvider;

    @Resource
    SecurityPermissionEvaluator securityPermissionEvaluator;

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * @Author Bernie
     * @Description 注入自定义PermissionEvaluator
     * @Date 16:33 2024/4/23
     * @return: org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler
     **/
    @Bean
    public DefaultWebSecurityExpressionHandler userSecurityExpressionHandler() {
        DefaultWebSecurityExpressionHandler handler = new DefaultWebSecurityExpressionHandler();
        handler.setPermissionEvaluator(securityPermissionEvaluator);
        return handler;
    }

    /**
     * @param auth:
     * @Author Bernie
     * @Description 配置启用我们自己的登陆验证逻辑
     * @Date 16:34 2024/4/23
     * @return: void
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) {
        auth.authenticationProvider(securityAuthenticationProvider);
    }

    /**
     * 配置security的控制逻辑
     *
     * @Author Sans
     * @CreateTime 2019/10/1 16:56
     * @Param http 请求
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                // 不进行权限验证的请求或资源(从配置文件中读取)
                .antMatchers("/login", "/common/**").permitAll()
                // 其他的需要登陆后才能访问
                .anyRequest().authenticated()

                .and().httpBasic()
                .authenticationEntryPoint(authenticationEntryPoint) // 配置未登录自定义处理类

                .and().formLogin()
//                .loginProcessingUrl("/common/userLogin") // 配置登录地址
                .successHandler(authenticationSuccessHandler) // 配置登录成功自定义处理类
                .failureHandler(authenticationFailureHandler) // 配置登录失败自定义处理类

                .and().logout()
//                .logoutUrl("/login/userLogout") // 配置登出地址
                // 配置用户登出自定义处理类
                .logoutSuccessHandler(logoutSuccessHandler)

                .and().exceptionHandling()
                .accessDeniedHandler(accessDeniedHandler) // 配置没有权限自定义处理类
                .and()
                // 开启跨域
                .cors()
                .and()
                // 取消跨站请求伪造防护
                .csrf().disable();

        // 基于Token不需要session
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        // 禁用缓存
        http.headers().cacheControl();
        // 添加JWT过滤器
        http.addFilter(new JwtAuthenticationTokenFilter(authenticationManager()));
    }

}